<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <button @click="goBack" class="btn btn-secondary" style="position: absolute; left: 20px; z-index: 10;">← 返回</button>
      <img src="/logo.svg" alt="Logo" class="logo" />
      <div class="header-icon">
        <!-- 爱心图标 SVG -->
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="loveHeaderGradient" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" style="stop-color:#ff6b9d;stop-opacity:1" />
              <stop offset="50%" style="stop-color:#ff8fab;stop-opacity:1" />
              <stop offset="100%" style="stop-color:#ffa8cc;stop-opacity:1" />
            </linearGradient>
          </defs>
          <path d="M24 42L20.55 38.82C10.8 30.06 4.5 24.42 4.5 17.5C4.5 12.42 8.42 8.5 13.5 8.5C16.74 8.5 19.86 10.26 21.75 12.9C22.65 14.22 23.25 15.78 24 17.46C24.75 15.78 25.35 14.22 26.25 12.9C28.14 10.26 31.26 8.5 34.5 8.5C39.58 8.5 43.5 12.42 43.5 17.5C43.5 24.42 37.2 30.06 27.45 38.82L24 42Z" fill="url(#loveHeaderGradient)"/>
        </svg>
      </div>
      <span>AI恋爱大师</span>
      <div style="position: absolute; right: 20px; top: 50%; transform: translateY(-50%); font-size: 12px; opacity: 0.8;">
        会话ID: {{ chatId }}
      </div>
    </div>
    
    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
        <!-- 消息头像 -->
        <div class="message-avatar">
          <div v-if="message.type === 'user'" class="avatar user-avatar">
            <!-- 用户头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="userGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
              <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
              <circle cx="24" cy="18" r="5" fill="url(#userGradient)"/>
              <path d="M13 35c0-6.075 4.925-11 11-11s11 4.925 11 11" fill="url(#userGradient)"/>
            </svg>
          </div>
          <div v-else class="avatar ai-avatar">
            <!-- AI头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="aiLoveGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#a855f7;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
                </linearGradient>
              </defs>
              <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
              <path d="M24 32L21.5 29.8C15.8 24.6 12 21.2 12 17C12 13.5 14.9 10.6 18.4 10.6C20.3 10.6 22.1 11.6 23 13.1C23.9 11.6 25.7 10.6 27.6 10.6C31.1 10.6 34 13.5 34 17C34 21.2 30.2 24.6 24.5 29.8L24 32Z" fill="url(#aiLoveGradient)"/>
            </svg>
          </div>
        </div>
        
        <div class="message-wrapper">
          <!-- 如果是步骤消息，显示为多个气泡 -->
          <div v-if="message.isSteps" class="steps-container">
            <div v-for="(step, stepIndex) in message.steps" :key="stepIndex" class="message-content step-bubble">
              <div class="step-header">{{ step.header }}</div>
              <div class="step-content">{{ step.content }}</div>
            </div>
          </div>
          <!-- 普通消息显示 -->
          <div v-else class="message-content">
            {{ message.content }}
          </div>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="message ai">
        <div class="message-avatar">
          <div class="avatar ai-avatar">
            <!-- AI头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="aiLoveLoadingGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#a855f7;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
              </linearGradient>
            </defs>
            <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
            <path d="M24 32L21.5 29.8C15.8 24.6 12 21.2 12 17C12 13.5 14.9 10.6 18.4 10.6C20.3 10.6 22.1 11.6 23 13.1C23.9 11.6 25.7 10.6 27.6 10.6C31.1 10.6 34 13.5 34 17C34 21.2 30.2 24.6 24.5 29.8L24 32Z" fill="url(#aiLoveLoadingGradient)"/>
          </svg>
          </div>
        </div>
        <div class="message-wrapper">
          <div class="message-content">
            正在思考中...
          </div>
        </div>
      </div>
    </div>
    
    <!-- 聊天输入区域 -->
    <div class="chat-input">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage" 
        placeholder="请输入您的恋爱问题..." 
        :disabled="isLoading"
        ref="messageInput"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'LoveApp',
  data() {
    return {
      // 聊天会话ID
      chatId: '',
      // 聊天消息列表
      messages: [],
      // 输入框内容
      inputMessage: '',
      // 是否正在加载
      isLoading: false,
      // SSE连接
      eventSource: null
    }
  },
  
  mounted() {
    // 页面加载时生成聊天室ID
    this.generateChatId()
    // 发送欢迎消息
    this.addWelcomeMessage()
  },
  
  beforeUnmount() {
    // 组件销毁前关闭SSE连接
    this.closeEventSource()
  },
  
  methods: {
    /**
     * 生成唯一的聊天室ID
     */
    generateChatId() {
      this.chatId = 'love_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    },
    
    /**
     * 添加欢迎消息
     */
    addWelcomeMessage() {
      this.messages.push({
        type: 'ai',
        content: '你好！我是AI恋爱大师，专门为您提供恋爱咨询和情感建议。请告诉我您遇到的情感问题，我会尽力帮助您！💕'
      })
    },
    
    /**
     * 发送消息
     */
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) {
        return
      }
      
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息到聊天记录
      this.messages.push({
        type: 'user',
        content: userMessage
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      // 开始加载
      this.isLoading = true
      
      try {
        // 调用SSE接口
        await this.callLoveAppSSE(userMessage)
      } catch (error) {
        console.error('发送消息失败:', error)
        this.messages.push({
          type: 'ai',
          content: '抱歉，服务暂时不可用，请稍后再试。'
        })
        this.isLoading = false
      }
    },
    
    /**
     * 调用AI恋爱大师SSE接口
     */
    async callLoveAppSSE(message) {
      // 关闭之前的连接
      this.closeEventSource()
      
      // 根据环境变量设置 API 基础 URL
      const API_BASE_URL = process.env.NODE_ENV === 'production'
        ? '/api' // 生产环境使用相对路径，适用于前后端部署在同一域名下
        : 'http://localhost:8123/api' // 开发环境指向本地后端服务
      
      // 构建SSE URL
      const baseUrl = `${API_BASE_URL}/ai/love_app/chat/sse`
      const params = new URLSearchParams({
        message: message,
        chatId: this.chatId
      })
      const url = `${baseUrl}?${params}`
      
      // 创建EventSource连接
      this.eventSource = new EventSource(url)
      
      // 用于累积AI回复内容
      let aiResponse = ''
      let aiMessageIndex = -1
      
      // 监听消息事件
      this.eventSource.onmessage = (event) => {
        const data = event.data
        
        if (data === '[DONE]') {
          // 流式传输结束
          this.isLoading = false
          this.closeEventSource()
          return
        }
        
        // 累积AI回复内容
        aiResponse += data
        
        // 如果是第一次接收到数据，创建AI消息
        if (aiMessageIndex === -1) {
          const messageObj = this.parseStepsMessage(aiResponse)
          this.messages.push({
            type: 'ai',
            ...messageObj
          })
          aiMessageIndex = this.messages.length - 1
        } else {
          // 更新AI消息内容
          const messageObj = this.parseStepsMessage(aiResponse)
          this.messages[aiMessageIndex] = {
            type: 'ai',
            ...messageObj
          }
        }
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
      
      // 监听错误事件
      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        this.isLoading = false
        this.closeEventSource()
        
        if (aiMessageIndex === -1) {
          this.messages.push({
            type: 'ai',
            content: '抱歉，连接出现问题，请稍后再试。'
          })
        }
      }
      
      // 监听连接打开事件
      this.eventSource.onopen = () => {
        console.log('SSE连接已建立')
      }
    },
    
    /**
     * 关闭EventSource连接
     */
    closeEventSource() {
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
    },
    
    /**
     * 滚动到聊天底部
     */
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    
    /**
     * 解析步骤消息
     * 检测是否包含步骤格式（Step 1:, Step 2: 等），如果是则分解为多个步骤
     */
    parseStepsMessage(content) {
      // 更强大的步骤模式匹配：支持Step1:, Step 1:, Step1：, Step 1： 等格式
      const stepPattern = /Step\s*(\d+)\s*[：:]/gi
      const matches = [...content.matchAll(stepPattern)]
      
      if (matches.length === 0) {
        // 不是步骤格式，返回普通消息
        return {
          isSteps: false,
          content: content
        }
      }
      
      // 分割步骤
      const steps = []
      
      for (let i = 0; i < matches.length; i++) {
        const match = matches[i]
        const stepNumber = match[1]
        const stepStart = match.index
        const stepHeaderEnd = stepStart + match[0].length
        
        // 确定步骤内容的结束位置
        let stepEnd
        if (i < matches.length - 1) {
          // 不是最后一个步骤，内容到下一个步骤开始
          stepEnd = matches[i + 1].index
        } else {
          // 最后一个步骤，内容到字符串结束
          stepEnd = content.length
        }
        
        // 提取步骤内容
        const stepContent = content.substring(stepHeaderEnd, stepEnd).trim()
        
        // 创建步骤对象
        steps.push({
          header: `Step ${stepNumber}:`,
          content: stepContent
        })
      }
      
      // 过滤掉空内容的步骤
      const validSteps = steps.filter(step => step.content.length > 0)
      
      return {
        isSteps: validSteps.length > 0,
        steps: validSteps
      }
    },
    
    /**
     * 返回主页
     */
    goBack() {
      this.closeEventSource()
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
/* 组件特定样式已在全局样式中定义 */
</style>